﻿using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System;

namespace RSuite.R2
{
    public class MainForm : AwesomiumForm
    {
        public MainForm()
            : base("UI/R2.htm")
        {
        }

        protected override void InitForm(Form form)
        {
            form.Text = "R2 - Review";
            form.Icon = new Icon(@"UI\images\r4.ico");
            form.Width = 800;
            form.Height = 800;
            form.MinimumSize = new Size(400, 400);
        }

        protected override object InvokeLocalMethod(string method, dynamic data, string id)
        {
            switch (method)
            {
                case "open":
                    return this.Open(data);
                case "save":
                    return this.Save(data);
                default:
                    return string.Empty;
            }
        }

        private object Open(dynamic data)
        {
            var dialog = new OpenFileDialog();
            dialog.FileName = data;
            if (base.ShowDialog(dialog) != DialogResult.OK)
            {
                return string.Empty;
            }

            if (Path.GetExtension(dialog.FileName).ToLower() == ".rvw")
            {
                return new
                {
                    filename = dialog.FileName,
                    review = File.ReadAllText(dialog.FileName)
                };
            }
            else
            {
                return new
                {
                    filename = "",
                    review = base.ToJSON(new
                    {
                        codefile = Path.GetFileName(dialog.FileName),
                        code = File.ReadAllText(dialog.FileName),
                        reviewDate = DateTime.Today.ToString("yyyy/MM/dd HH:mm:ss")
                    })
                };
            }
        }

        private object Save(dynamic data)
        {
            var filename = data["filename"];
            if (string.IsNullOrEmpty(filename))
            {
                var dialog = new SaveFileDialog();
                if (base.ShowDialog(dialog) != DialogResult.OK)
                {
                    return string.Empty;
                }
                filename = dialog.FileName;
            }

            File.WriteAllText(filename, (string)data["review"]);
            return filename;
        }
    }
}